from utils.log import logger
import json
# "同期值","同期增长","同比","同期增长率","年累","年累同期值","年累同期增量","年累同期增长率",
# "季累","季累同期值","季累同期增量","季累同期增长率","月累","月累同期值","月累同期增量","月累同期增长率",
# "环比","环比增长率","前期增长","前期值"

class MDXRecognition:
    #初始化，先把所有mdx的候选列表存下来
    def __init__(self, model) -> None:
        self.model = model
        self.prompt ="假设你是一个特殊指标预测器，给你一个查询语句和一个查询中的列名，需要输出这个列名对应的特殊指标。以下是候选答案：\
    同期值，同期增长，同比，同期增长率，年累，年累同期值，年累同期增量，年累同期增长率，季累，季累同期值，季累同期增量，季累同期增长率，\
    月累，月累同期值，月累同期增量，月累同期增长率，环比，环比增长率，前期增长，前期值。如果该列名没有对应的聚合函数则输出none \
    注意不要输出解释性文本。输入查询：{}，输入列名：{}；\n输出： "
        self.mdx_list=["同期值","同期增长","同比","同期增长率","年累","年累同期值","年累同期增量","年累同期增长率",
"季累","季累同期值","季累同期增量","季累同期增长率","月累","月累同期值","月累同期增量","月累同期增长率",
"环比","环比增长率","前期增长","前期值"]
    def recognition(self,query,sel,measure):
        processed=[]
        origin=[]
        time_level_id=self.get_min_time_level(sel)
        for header in sel:
            id=header['id']
            name=header['name']
            if id not in measure:
                continue
            intput_prompt = self.prompt.format(query,name)
            try:
                output=self.model.predict(intput_prompt)
                origin.append({name:output})
            except Exception as err:
                logger.error("MDX recognition init error[{}]: {}".format(type(err), str(err)))
                raise
            if output=='none' or output not in self.mdx_list:
                continue
            else:
                processed.append(self.combine_func(id,name,time_level_id,output))
        return {'origin':origin,'processed':{'mdx':processed}}
    #按照年季月日的顺序找到查询中的最小时间单位
    def get_min_time_level(self,sel):
        time_level_id=''
        tmp_time_level=0
        for header in sel:
            name=header['name']
            id=header['id']
            if name=='日':
                time_level_id=id
                break
            elif name=='月':
                time_level_id=id
                tmp_time_level=3
            elif name=='季' and tmp_time_level<=1:
                time_level_id=id
                tmp_time_level=2
            elif name=='年' and tmp_time_level==0:
                time_level_id=id
                tmp_time_level=1
        try:
            if time_level_id=='':
                raise Exception("没加time_level")
        except Exception as err:
            logger.error(err)
            raise

        return time_level_id
    #将header和模型输出组合成规定格式的数据字典
    def combine_func(self, measure_id,measure_name,time_level_id,op_name):
        ans_dict={}
        ans_dict['function_name']=op_name
        ans_dict['id']=measure_name+op_name
        ans_dict['name']=measure_name+op_name
        ans_dict['type']='MEASURE'
        ans_dict['member_amount']=0
        ans_dict['param']={}
        ans_dict['param']['time_id']=time_level_id
        ans_dict['param']['measure_id']=measure_id
        return ans_dict
